/**
 * 
 */
package com.googlecode.xcarve.netty.handler;


import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.googlecode.xcarve.common.config.CarveConstances;
import com.googlecode.xcarve.netty.core.DoveFuture;
import com.googlecode.xcarve.object.NettyMessage;
import com.googlecode.xcarve.object.RPCReponse;

/**
 * @author hello_yun 2014-7-9
 */
@Sharable
public class NettyClientHandler extends ChannelHandlerAdapter {
	static final Logger logger = LoggerFactory.getLogger(NettyClientHandler.class);
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		final Channel channle = ctx.channel();
		channle.attr(AttributeKey.<Long>valueOf(CarveConstances.LAST_READ_TIME)).set(System.currentTimeMillis());
		NettyMessage nettyMsg = (NettyMessage)msg;
		Object body = nettyMsg.getBody();
//		logger.info("client request msg = "+body);
		if(body != null && body instanceof RPCReponse){
			DoveFuture.readResponse((RPCReponse)body);	
		}
		
	}
 
 
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		ctx.fireExceptionCaught(cause);
		logger.error("catched exception............ ",cause);
		if(ctx.channel().isActive()){
			logger.info("close ctx.");
			ctx.channel().close().awaitUninterruptibly(CarveConstances.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
		}
		
	}
	
	 
}
